package com.whz.mutithread;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * @Author: sinosoft
 * @Description: 实现一个可以观察到的集合包装
 * 该类允许客户端在将元素添加到集合中时预订通知
 * @Date: Create in 15:09 2021/5/25
 * @Modified By:
 */
public class ObservableSet<E> extends ForwardingSet<E> {
    public ObservableSet(Set<E> s) {
        super(s);
    }
    private final List<SetObserver<E>> observers = new ArrayList<>();
    public void addObserver(SetObserver<E> observer) {
        observers.add(observer);
    }
    public boolean removeObserver(SetObserver<E> observer) {
        synchronized (observers) {
            return observers.remove(observer);
        }
    }
    private void notifyElementAdded(E element) {
        synchronized (observers) {
            for (SetObserver<E> observer : observers) {
                observer.added(this, element);
            }
        }
    }
    @Override
    public boolean add(E element) {
        boolean added = super.add(element);
        if(added) {
            notifyElementAdded(element);
        }
        return added;
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {
        boolean result = false;
        for (E element : c) {
            result |= add(element);
        }
        return result;
    }

}
